// pages/shopping/goodsShare/goodsShare.js
var app = getApp();
var bg_pic= '';
var save_path= '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareBg: '../../../images/share_bg.jpg',
    userPic: '../../../images/user_pic_share.png',
    messageIcon: '../../../images/message_icon.png',
    messageIcon1: '../../../images/message_icon_1.png',
    code: '../../../images/code.png',
    userName: '韩梅梅',
    messageInfo: '365',
    defaultSize: 'default',
    canvas_w: 0,
    canvas_h: 0,
    btn_h: 0,
    equipments_id: '', //缴费器id
    equipments: {},
    main_pic: '',
    qrcode: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log(options)
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    that.setData({
      equipments_id: options.equipments_id
    })
    that.getQr();


  },
  //生成页面二维码pages/shopping/goodsDetail/goodsDetail
  getQr() {
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    var pro = wx.getStorageSync('promoter');
    var cha = wx.getStorageSync('channel');
    app.createQrcode('eq_id=' + that.data.equipments_id + "&pid=" + user_id + "&way=4"+"&pro="+pro+"&cha="+cha, 'pages/shopping/goodsDetail/goodsDetail', function(url) {
      console.log(url)
      wx.downloadFile({
        url: url,
        success: function(res) {
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            that.setData({
              qrcode: res.tempFilePath
            })
            that.getGoodsDetail();
          }
        }
      })
    });
  },

  //查询商品详情
  getGoodsDetail() {
    var that = this;
    var equipments_id = that.data.equipments_id;
    app.ajax({
      url: 'User/Equipment/equipmentsDetail',
      method: "POST",
      data: {
        equipments_id: equipments_id
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var article = res.data.data.detail;
          that.setData({
            equipments: res.data.data
          })
          wx.getImageInfo({ //  小程序获取图片信息API
            src: res.data.data.main_pic,
            success: function(res) {
              bg_pic = res.path
              that.getShareCanvas(res.path);
            }
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //生成canvas
  getShareCanvas() {
    var that = this;
    //console.log(bg_pic)
    //var main_pic = that.data.shareBg;
    console.log(that.data.qrcode)
    var main_pic = that.data.qrcode;
    //console.log(main_pic);
    wx.getImageInfo({
      src: main_pic,
      success: function(res) {
        //console.log(res)
        //console.log(res.width)
        //console.log(res.height)
        const ctx = wx.createCanvasContext('shareCanvas');
        ctx.clearRect(0, 0, 0, 0);
        const WIDTH = Number(wx.getSystemInfoSync().windowWidth) * 0.7;
        const HEIGHT = WIDTH * 1.4;
        const left_height = HEIGHT - WIDTH //canvas除图片外的高度
        const btn_h = Number(wx.getSystemInfoSync().windowHeight);
        const code_width = left_height - 20 //二维码宽度
        that.setData({
          canvas_w: WIDTH,
          canvas_h: HEIGHT,
          btn_h: btn_h
        })
        ctx.fillStyle='white';
        ctx.fillRect(0, 0, WIDTH, HEIGHT)
        ctx.drawImage(bg_pic, 0, 0, WIDTH, WIDTH);
        //console.log(code_width/6)

        var size = 8;
        var boxWidth = WIDTH - code_width - 30;
        size = parseInt(code_width / 6 / 10) * size * 0.9;
        var initHeight = WIDTH + 10 + size / 2;
        var height_line = code_width / 6 + size / 2;
        var str = that.data.equipments.equipments_name;
        fillAllText(ctx, str, initHeight, boxWidth, size * 1.4, '#4c4c4c', 0, 1, height_line, 'middle')

        initHeight += height_line;
        //console.log(initHeight)
        var str = that.data.equipments.brief_desc;
        fillAllText(ctx, str, initHeight, boxWidth, size * 1.2, '#808080', 0, 2, height_line, 'middle')


        initHeight += height_line * 1.8;
        var tips = that.data.equipments.label;
        var sum = 0;
        for (var i = 0; i < tips.length; i++) {
          var w = ctx.measureText(tips[i]).width + 5
          sum += w;
          fillAllText(ctx, tips[i], initHeight, boxWidth, size * 1.2, '#6da9ff', sum - w, 1, height_line, 'middle')
          console.log('wwwwwwwww', sum)
        }

        initHeight += height_line;
        var money = that.data.equipments.equipments_money;
        if (that.data.equipments.equipments_type == 2) {
          money = that.data.equipments.equipments_purchase_money;
        }

        var str = '￥' + money + '起';
        fillAllText(ctx, str, initHeight, boxWidth, size * 2, '#c80000', 0, 1, height_line, 'middle')

        const metrics = ctx.measureText(str)

        var str = that.data.equipments.equipments_orgin_money;
        fillAllText(ctx, str, initHeight, boxWidth, size * 1.2, '#808080', metrics.width + 10, 1, height_line, 'middle')
        const metrics1 = ctx.measureText(str)
        ctx.beginPath()
        ctx.moveTo(metrics.width + 20, initHeight)
        ctx.lineTo(metrics1.width + metrics.width + 20, initHeight)
        ctx.strokeStyle='#808080'
        ctx.stroke()

        initHeight += height_line;
        //console.log(initHeight)
        var str = '需支付押金' + that.data.equipments.deposit + '元';
        fillAllText(ctx, str, initHeight, boxWidth, size * 1.2, '#5c5c5c', 0, 1, 'middle')
        ctx.drawImage(res.path, WIDTH - code_width - 10, WIDTH + 10, code_width, code_width)
        ctx.draw();
        //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function() {
          wx.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success: function(res) {
              wx.hideLoading()
              var tempFilePath = res.tempFilePath;
              save_path= res.tempFilePath
            },
            fail: function(res) {
              //console.log(res);
            }
          });
        }, 500);
      }
    })

    function fillAllText(ctx, str, initHeight, boxWidth, size, color, offset, l, height_line, line) {
      /*
      ctx:canvas实例
      str:text字符串
      initHeight:位置高度
      boxWidth:文本大小
      size:字体大小
      color:字体颜色
      offset:字体偏移量
      l:显示行数
      */
      //console.log('initHeight:'+initHeight)
      console.log('字体大小',size);
      ctx.font=size+'px';
      ctx.fillStyle=color;
      ctx.setTextBaseline(line)
      var lineWidth = 0; //字符串长度
      var lastSubStrIndex = 0;
      var h = 1;
      for (let i = 0; i < str.length; i++) {
        //console.log(ctx.measureText(str[i]).width)
        lineWidth += ctx.measureText(str[i]).width;
        //console.log(lineWidth)
        //console.log(boxWidth)
        //console.log(str[i])

        if (h < l + 1) {
          if (lineWidth > boxWidth) {
            //console.log(str[i])
            //console.log(h);
            //console.log(l);
            if (h == l) {
              var str = str.substring(0, i - 3) + '...';
            }
            ctx.fillText(str.substring(lastSubStrIndex, i), 10 + offset, initHeight); //绘制截取部分
            initHeight += height_line + 0; //20为字体的高度
            lineWidth = 0;
            lastSubStrIndex = i;
            h++;
          }
          if (i == str.length - 1) {
            //绘制剩余部分
            ctx.fillText(str.substring(lastSubStrIndex, i + 1), 10 + offset, initHeight);
            h++;
          }
        }
      }
    }
  },
  //保存二维码
  saveCode: function() {
    wx.saveImageToPhotosAlbum({
      filePath: save_path,
      success(res) {
        //console.log(res)
        app.showToast('图片保存成功');
        wx.navigateBack({
          delta: 1
        })
      }
    })
    // wx.downloadFile({
    //   url: '', //仅为示例，并非真实的资源
    //   success: function (res) {
    //     // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
    //     if (res.statusCode === 200) {
    //       wx.saveImageToPhotosAlbum({
    //         filePath: res.tempFilePath,
    //         success: function (res) {
    //           console.log(res)
    //         },
    //         fail: function (res) {
    //           console.log(res)
    //           console.log('fail')
    //         }
    //       })
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res)
    //     console.log('fail')
    //   }
    // })

  },

})
